package com.example.broadcast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private IntentFilter intentFilter;

    private NetworkChangeReceiver networkChangeReceiver;

    private LocalReceiver localReceiver;

    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        intentFilter = new IntentFilter();
        // 当网络变化时，系统会发出android.net.conn.CONNECTIVITY_CHANGE的广播，这里是将广播的action
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver = new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver, intentFilter); // 将要接受广播和对应的类方法到注册其中

        //自定义广播部分
        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("data", "Hello ");
                intent.setAction("com.example.broadcast.MY_BROADCAST");
                intent.setPackage(getPackageName()); // android8.0 以后需要加上这句代码，否则就接收不到广播·
                sendBroadcast(intent);
                Log.i(TAG, "onClick: send broadcast.");
            }
        });

        /**
         * 本地广播
         */
        localBroadcastManager=LocalBroadcastManager.getInstance(this); // 获取实例
        findViewById(R.id.Local_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcast.LOCAL_BROADCAST");
                intent.setPackage(getPackageName());
                localBroadcastManager.sendBroadcast(intent); // 发送本地广播
                Log.i(TAG, "onClick: send local broadcast.");
            }
        });
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcast.MY_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter); // 注册本地广播接听器

    }


    /**
     * 动态广播
     */
    class NetworkChangeReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show();

            /**
             * 改进：只是弹窗对用户不友好，我们需要知道具体的网络情况
             */
            // 获得一个系统服务类，专门用于网络管理连接的
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(context.CONNECTIVITY_SERVICE);
            // 获取到 networkInfo实例
            // 注意这里由于系统隐私的需求，需加上网络的权限声明：<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
                Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销该网络接收器
        localBroadcastManager.unregisterReceiver(localReceiver);
    }
    /**
     * 本地广播
     */
    class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
        }
    }

}